import re
import urllib2
from modeldata import ModelData

#SQLite does not define a longitude or max lenght for data types, so basing on a equivalences table found here:
#http://www.sqlite.org/datatype3.html we compare datatypes from schema to generate the new tables in the SQLite database.
integers = {'INT','INTEGER','TINYINT','SMALLINT','MEDIUMINT','BIGINT','UNSIGNED BIG INT','INT2','INT8' }
texts = {'CHARACTER','VARCHAR','VARYING CHARACTER','NCHAR','NATIVE CHARACTER','NVARCHAR','TEXT','CLOB' }
blobs = {'BLOB'}
reals = {'REAL','DOUBLE','DOUBLE PRECISION','FLOAT' }
numerics = {'NUMERIC','DECIMAL','BOOLEAN','DATE','DATETIME' }
URL_ADDRESS = 'http://localhost/dumper-php/dump.php'

class JSONParser:
    
    _data = list()
    _primarykey = None
    _columnsstring = None
    _tables = list()
    _model = None
    
    def __init__(self):
        print 'JSON Parser generated'
        self._model = ModelData()
        
    def getTables(self):
        print 'getTables'
        print self._tables
        return self._tables
    
    def getTypeWithArray(self,mystring,myarray):
        found = False
        for element in myarray:
            saux = ".*"+element+".*"
            mo = re.match(saux, mystring)
            if mo:
                found = True
                break
                
        return found
    
    #with this function we will select the data type of the column, checking it out with arrays above.
    def getType(self,mystring):
        if self.getTypeWithArray(mystring,integers):
            return 'INTEGER'
        if self.getTypeWithArray(mystring,texts):
            return 'TEXT'
        if self.getTypeWithArray(mystring,blobs):
            return 'BLOB'
        if self.getTypeWithArray(mystring,reals):
            return 'REAL'
        if self.getTypeWithArray(mystring,numerics):
            return 'NUMERIC'
        
    def check(self,mo3,n):
        if mo3.group(n-1) == '"primarykey"':
            self._primarykey = "\"" + mo3.group(n) + "\"";
        else:
            auxstring = mo3.group(n-1) + ' ' + self.getType(mo3.group(n).upper())
            if mo3.group(n - 1) == self._primarykey:
                auxstring += ' PRIMARY KEY'
            self._data.append(auxstring)
            print self._data
        if n == 3:
            self._columnsstring = mo3.group(1)
            mo3 = re.match("(.*), (.*): \"(.*)\"",mo3.group(1))
        return mo3

    def parseTable(self, schema):
        self._data = list()
        mo2 = re.match(".*columns\": {(.*)} } }",schema)
        if mo2:
            self._columnsstring = mo2.group(1)
            mo3 = re.match("(.*), (.*): \"(.*)\"",self._columnsstring)
            while mo3:
                mo3 = self.check(mo3,3)
            mo3 = re.match(" (.*): \"(.*)\"",self._columnsstring)
            if mo3:
                self.check(mo3,2)
        else:
            mo2 = re.match(".*columns\": {(.*)}",schema)
            if mo2:
                self._columnsstring = mo2.group(1)
                mo3 = re.match("(.*), (.*): \"(.*)\"",self._columnsstring)
                while mo3:
                    mo3 = self.check(mo3,3)
                mo3 = re.match(" (.*): \"(.*)\"",self._columnsstring)
                if mo3:
                    self.check(mo3,2)
        #as the parser reads columns from tail to head, now we have to reverse elements
        self._data.reverse()
        return self._data
    
    def parseSchema(self, schema):
        mo = re.match("(.*)\"(.*)\".*{.*(\"columns.*)",schema)
        resto = ''
        while (mo):
            resto = mo.group(1)
            self._tables.append(mo.group(2))
            self._model.createTable(mo.group(2), self.parseTable(mo.group(3)))
            mo = re.match("(.*)\"(.*)\".*{.*(\"columns.*)",resto)
            
    def parseData(self):
        print 'parseData...'
        print self._tables
        for n in self._tables:
            print 'b'
            url = URL_ADDRESS + '?service=getdata&table='+n+'&output=json'
            print url
            f = urllib2.urlopen(url)
            data = f.read()
            print 'data = ' + data
        